package offer

import (
	// "bp/cache"
	sqlc "bp/db/sqlc"
	"bp/internal/util"
)

// 带上限的折扣
func (s *OfferComServiceImp) discountOffWithOffMaximum(amount, price, off_maximum int32) int32 {
	off := util.RoundToInt32(float64(amount*(100-price)) / float64(100))
	return util.Int32IfThenElse(off > off_maximum, off_maximum, off)
}

// 带上限的折扣
func (s *OfferComServiceImp) discountOffWithoutOffMaximum(amount, price int32) int32 {
	return util.RoundToInt32(float64(amount*(100-price)) / float64(100))
}

// 减价
func (s *OfferComServiceImp) cutOff(amount, price int32) int32 {
	return util.Int32IfThenElse(amount-price > 0, price, amount)
}

// 秒杀,特价
func (s *OfferComServiceImp) limitOff(amount, price int32) int32 {
	return amount - price
}

// 满减
func (s *OfferComServiceImp) quotaCutOff(amount, price, quota int32) int32 {
	if quota > amount {
		return 0
	}
	return s.cutOff(amount, price)
}

// 每满减
func (s *OfferComServiceImp) quotaCutOffRepeated(amount, price, quota, off_maximum int32) int32 {
	if quota > amount {
		return 0
	}
	n := util.FloorToInt(float64(amount) / float64(quota))
	var off int32
	for i := 0; i < n; i++ {
		off += s.cutOff(amount, price)
	}
	return off
}

// 促销活动计算优惠金额
func (s *OfferComServiceImp) promotionOff(amount int32, ptr *sqlc.Promotion) (off int32) {
	switch sqlc.EmOfferType(ptr.OfferType) {
	case sqlc.EmOfferTypeDiscount:
		return s.discountOffWithOffMaximum(amount, ptr.Price, ptr.OffMaximum)
	case sqlc.EmOfferTypeCut:
		return s.cutOff(amount, ptr.Price)
	case sqlc.EmOfferTypeLimit:
		return s.limitOff(amount, ptr.Price)
	case sqlc.EmOfferTypeQuotaCut:
		s.slog.Infof("ptr.GradientRules:%d", len(ptr.GradientRules))
		if len(ptr.GradientRules) == 0 {
			return s.quotaCutOffRepeated(amount, ptr.Price, ptr.Quota, ptr.OffMaximum)
		} else {
			// 因确保存储到数据库内已经按照quota降序
			for _, r := range ptr.GradientRules {
				if amount >= r.Quota {
					return s.quotaCutOff(amount, r.Price, r.Quota)
				}
			}
		}
	}
	return
}

// 会员优惠券计算优惠金额
func (s *OfferComServiceImp) memberCouponOff(amount int32, ptr *sqlc.MemberCoupon) (off int32) {
	switch sqlc.EmOfferType(ptr.OfferType) {
	case sqlc.EmOfferTypeDiscount:
		return s.discountOffWithOffMaximum(amount, ptr.Price, ptr.OffMaximum)
	case sqlc.EmOfferTypeCut, sqlc.EmOfferTypeQuotaCut:
		s.slog.Infof("amount:%d, %d, %d", amount, ptr.Price, s.cutOff(amount, ptr.Price))
		return s.cutOff(amount, ptr.Price)
	case sqlc.EmOfferTypeLimit:
		return s.limitOff(amount, ptr.Price)
	}
	return
}

// 会员优惠券计算优惠金额
func (s *OfferComServiceImp) cardDiscountOff(amount int32, ptr *sqlc.CardDiscount) (off int32) {
	return s.discountOffWithoutOffMaximum(amount, ptr.Discount)
}
